var _columns = [
    {checkbox: true},
    {field: 'id', title: '标示符', align: 'center', valign: 'middle'},
    {
        title: '序号', field: 'showId', align: 'center', valign: 'middle',
        formatter: function (value, row, index) {
            return index + 1;
        }
    },
    {field: 'pollutants', title: '污染物项目'},
    {field: 'requirement', title: '一般/特别要求'},
    {field: 'dischargeType', title: '排放类型'},
    {field: 'limitValue', title: '限值'},
    {field: 'unit', title: '单位'},
    {field: 'dischargeConcentration', title: '排放浓度'},
    {field: 'position', title: '污染物排放监控位置'},
    {field: 'note', title: '备注'},
]

var metaList;
var selectButton;   //新增按钮还是编辑按钮

var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/waste_water_sub/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            onLoadSuccess: function (data) {
                var num = $('#data_table').bootstrapTable('getOptions').totalRows;
                if (num != 0) {
                    addTableFoot();
                    changeTableFoot();
                }
            }
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            lastId: lastId
        };
        return temp;
    };
    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {
        //初始化页面上面的按钮事件
        //新增按钮
        $("#btn_add").click(function () {
            selectButton = "insert";
            $('#company_type').val();
            $('#pollutants').val("");
            $('#requirement').val("");
            $('#discharge_type').val("");
            $('#limit_value').val("");
            $('#unit').val("");
            $('#discharge_concentration').val("");
            $('#position').val("");
            $('#note').val("");

            //设置模态框title
            var title = document.getElementById("title");
            title.innerHTML = "新增一项废水评估";

            $('#data').modal();

            //将企业类型插入选择框
            insertCompanyType()

        });

        //编辑按钮
        $("#btn_edit").click(function () {
            selectButton = "update";
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            } else if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            //设置模态框title
            var title = document.getElementById("title");
            title.innerHTML = "编辑一项废水评估";

            //将企业类型插入选择框
            insertCompanyType()

            $('#pollutants').val(arrselections[0].pollutants);
            getRequirement();   // 将要求加入选择框
            $('#requirement').val(arrselections[0].requirement);
            getDischargeType(); //将排放类型加入选择框
            $('#discharge_type').val(arrselections[0].dischargeType);

            $('#limit_value').val(arrselections[0].limitValue);
            $('#unit').val(arrselections[0].unit);
            $('#discharge_concentration').val(arrselections[0].dischargeConcentration);
            $('#position').val(arrselections[0].position);
            $('#note').val(arrselections[0].note);

            $('#data').modal();
        });

        //模态框内的提交按钮
        $('#data_submit').on('click', function () {

            var pollutants = $('#pollutants').val();
            var requirement = $('#requirement').val();
            var dischargeType = $('#discharge_type').val();
            var limitValue = $('#limit_value').val();
            var unit = $('#unit').val();
            var dischargeConcentration = $('#discharge_concentration').val();
            var position = $('#position').val();
            var note = $('#note').val();

            if (pollutants == "") {
                bootoast({
                    message: '请输入污染物项目',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            if (selectButton == "insert") {
                $.ajax({
                    type: "post",
                    url: "/waste_water_sub/insert",
                    async: false,
                    data: {
                        'pollutants': pollutants,
                        'requirement': requirement,
                        'dischargeType': dischargeType,
                        'limitValue': limitValue,
                        'unit': unit,
                        'dischargeConcentration': dischargeConcentration,
                        'position': position,
                        'note': note,
                        'lastId': lastId
                    },
                    success: function (data) {
                        bootoast({
                            message: '插入成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#data_table").bootstrapTable('refresh');
                        $('#data').modal('hide');
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            } else if (selectButton == "update") {
                var id = $("#data_table").bootstrapTable('getSelections')[0].id;
                $.ajax({
                    type: "post",
                    url: "/waste_water_sub/update",
                    async: false,
                    data: {
                        'id': id,
                        'pollutants': pollutants,
                        'requirement': requirement,
                        'dischargeType': dischargeType,
                        'limitValue': limitValue,
                        'unit': unit,
                        'dischargeConcentration': dischargeConcentration,
                        'position': position,
                        'note': note
                    },
                    success: function (data) {
                        bootoast({
                            message: '更新成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#data_table").bootstrapTable('refresh');
                        $('#data').modal('hide');
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            }
        });

        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            ids = [];
            for (var i = 0; i < arrselections.length; i++)
                ids.push(arrselections[i].id);

            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/waste_water_sub/delete",
                            async: false,
                            data: JSON.stringify(ids),
                            contentType: "application/json",
                            success: function (data) {
                                bootoast({
                                    message: '删除成功',
                                    position: 'top',
                                    type: 'success',
                                    timeout: 1.5,
                                });
                                $("#data_table").bootstrapTable('refresh');
                            },
                            error: function () {
                                bootoast({
                                    message: '通讯异常',
                                    position: 'top',
                                    type: 'danger',
                                    timeout: 1.5,
                                });
                            }
                        });
                    }
                }
            })
        });

        // 返回按钮
        $("#btn_return").click(function () {
            if (operation == 'view') $('#page-wrapper').load("pages/entity_eva_waste_water_main.html")
            else if (operation == 'edit') $('#page-wrapper').load("pages/waste_water.html")
        });

        // 取消按钮
        $("#cancel").click(function () {
            $.ajax({
                type: 'post',
                url: '/waste_water_sub/update_state',
                async: false,
                data: {
                    state: "填写中",
                    id: lastId,
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
            $('#page-wrapper').load("pages/entity_eva_waste_water_main.html");
        });

        // 提交按钮
        $("#submit").click(function () {
            $.ajax({
                type: 'post',
                url: '/waste_water_sub/update_state',
                async: false,
                data: {
                    state: "已完成",
                    id: lastId,
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
            $('#page-wrapper').load("pages/entity_eva_waste_water_main.html");
        });
    };
    return oInit;
};

var hasPermission = function () {
    queryPermission('废水评估', '新增', 'btn_add')
    queryPermission('废水评估', '编辑', 'btn_edit')
    queryPermission('废水评估', '删除', 'btn_delete')
}

$(function () {
    hasPermission();

    // 获取水污染物排放浓度限值数据
    getMetaData();

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    //查看操作，隐藏按钮
    if (operation == 'view') {
        $('#btn_add').hide();
        $('#btn_edit').hide();
        $('#btn_delete').hide();
        $('#submit').hide();
        $('#cancel').hide();
    } else if (operation == 'export') {
        $('#btn_return').hide();
        $('#btn_add').hide();
        $('#btn_edit').hide();
        $('#btn_delete').hide();
        $('#submit').hide();
        $('#cancel').hide();
        bootbox.confirm({
            message: "确认导出？",
            locale: 'zh_CN',
            title: '操作提示',
            callback: function (result) {
                if (result) {
                    $("#data_table").tableExport({fileName: '废水评估', type: "xls", escape: "false"});
                    $('#page-wrapper').load("pages/entity_eva_waste_water_main.html");
                } else {
                    $('#page-wrapper').load("pages/entity_eva_waste_water_main.html");
                }
            }
        });
    }

    //3.隐藏列
    $('#data_table').bootstrapTable('hideColumn', 'id');

});

function getMetaData() {
    $.ajax({
        type: 'get',
        async: false,
        url: '/waste_water_sub/get_meta_data',
        data: {"stdNumber": stdNumber},
        success: function (data) {
            metaList = data;
            // console.log(metaList)
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
}

//将企业类型插入选择框
function insertCompanyType() {
    var companyType = document.getElementById("company_type");
    companyType.add(new Option("现有企业", "现有企业"));
    companyType.add(new Option("新建企业", "新建企业"));
    companyType.add(new Option("特别企业", "特别企业"));
}

//将污染物项目插入选择框
function getPollutants() {
    var companyType = $('#company_type').val();
    var pollutantsList = [];
    for (var i = 0; i < metaList.length; i++) {
        var flag = 1;   //需要插入
        for (var j = 0; j < pollutantsList.length; j++) {
            if (pollutantsList[j] == metaList[i].wasteEvent) {
                flag = 0;
                break;
            }
        }
        //需要插入
        if (flag == 1 && companyType == metaList[i].companyClass) {
            pollutantsList.push(metaList[i].wasteEvent);
        }
    }

    //插入到选择框
    var pollutants = document.getElementById("pollutants");
    pollutants.options.length = 1;
    for (var e in pollutantsList) {
        pollutants.add(new Option(pollutantsList[e], pollutantsList[e]));
    }
}

//根据企业类型和污染物项目，将一般/特别要求插入选择框
function getRequirement() {
    var companyType = $('#company_type').val();
    var pollutants = $('#pollutants').val();
    var requirementList = [];
    for (var i = 0; i < metaList.length; i++) {
        var flag = 1;
        for (var j = 0; j < requirementList.length; j++) {
            if (requirementList[j] == metaList[i].require) {
                flag = 0;
                break;
            }
        }
        if (flag == 1 && metaList[i].wasteEvent == pollutants && metaList[i].companyClass == companyType) {
            requirementList.push(metaList[i].require)
        }
    }

    //插入到选择框
    var requirement = document.getElementById("requirement");
    requirement.options.length = 1;
    for (var e in requirementList) {
        requirement.add(new Option(requirementList[e], requirementList[e]));
    }
}

//根据企业类型和污染物项目和要求，将排放类型加入选择框
function getDischargeType() {
    var companyType = $('#company_type').val();
    var pollutants = $('#pollutants').val();
    var requirement = $('#requirement').val();
    var dischargeTypeList = [];
    for (var i = 0; i < metaList.length; i++) {
        var flag = 1;
        for (var j = 0; j < dischargeTypeList.length; j++) {
            if (dischargeTypeList[j] == metaList[i].dischargeClass) {
                flag = 0;
                break;
            }
        }
        if (flag == 1 && metaList[i].wasteEvent == pollutants && metaList[i].require == requirement && metaList[i].companyClass == companyType) {
            dischargeTypeList.push(metaList[i].dischargeClass);
        }
    }
//       console.log(dischargeTypeList)
    var dischargeType = document.getElementById("discharge_type");
    dischargeType.options.length = 1;
    for (var e in dischargeTypeList) {
        dischargeType.add(new Option(dischargeTypeList[e], dischargeTypeList[e]));
    }
}

//选择污染物项目之前，先选择企业类型
function pollutantsCheck() {
    if ($('#company_type').val() == '') {
        alert("请先选择企业类型");
    }
}

//选择一般/特别要求之前，先选择污染物项目
function requirementCheck() {
    if ($('#pollutants').val() == "") {
        alert("请先选择污染物项目");
    }
}

//选择排放类型之前，先选择要求
function dischargeTypeCheck() {
    if ($('#requirement').val() == "") {
        alert("请先选择一般/特别要求");
    }
}

function companyTypeChange() {
    //清空污染物项目、一般/特别要求和排放类型
    document.getElementById('pollutants').length = 1
    document.getElementById("requirement").length = 1;
    document.getElementById("discharge_type").length = 1;

    //限值、单位和污染物排放监控位置清空
    $('#limit_value').val("");
    $('#unit').val("");
    $('#position').val("");

    getPollutants();
}

//污染物项目发生改变
function pollutantsChange() {
    var requirement = document.getElementById("requirement");
    var dischargeType = document.getElementById("discharge_type");

    //requirement和dischargeType清空
    requirement.options.length = 1;
    dischargeType.options.length = 1;

    //限值、单位和污染物排放监控位置清空
    $('#limit_value').val("");
    $('#unit').val("");
    $('#position').val("");

    // 重新选择requirement
    getRequirement();
}

//要求发生改变
function requirementChange() {
    var dischargeType = document.getElementById("discharge_type");

    //dischargeType清空
    dischargeType.options.length = 1;

    //限值、单位和污染物排放监控位置清空
    $('#limit_value').val("");
    $('#unit').val("");
    $('#position').val("");

    // 重新选择requirement
    getDischargeType();
}

//排放类型发生改变，改变对应的限值、单位和污染物排放监控位置
function dischargeTypeChange() {
    var pollutants = document.getElementById("pollutants");
    var requirement = document.getElementById("requirement");
    var dischargeType = document.getElementById("discharge_type");
    if (dischargeType.value == "") {
        $('#limit_value').val("");
        $('#unit').val("");
        $('#position').val("");
    } else {
        for (var i = 0; i < metaList.length; i++) {
            if (metaList[i].wasteEvent == pollutants.value && metaList[i].require == requirement.value && metaList[i].dischargeClass == dischargeType.value) {
                if (metaList[i].watermax == metaList[i].watermin) {
                    $('#limit_value').val(metaList[i].watermax);
                } else {
                    $('#limit_value').val(String(metaList[i].watermin) + "-" + String(metaList[i].watermax));
                }
                $('#unit').val(metaList[i].unit);
                $('#position').val(metaList[i].position);
            }
        }
    }
}

//添加表尾
function addTableFoot() {
    $('#tfoot').remove();
    $('#data_table').append('<tfoot id="tfoot">\
        <tr>\
            <th id="text" style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner">判断结果</div><div class="fht-cell"/></th>\
            <th id="result" style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner"></div><div class="fht-cell"/></th>\
        </tr>\
    </tfoot>\
	');
    $('#text').attr('colspan', 3);
    $('#result').attr('colspan', 6);
}

function changeTableFoot() {
    var data = $('#data_table').bootstrapTable('getData', false);//获取全部数据
    var flag = 1;   //表示达标
    for (var i = 0; i < data.length; i++) {

        var value;
        if (computeResult <= 1) value = parseFloat(data[i].dischargeConcentration);
        else value = computeResult * parseFloat(data[i].dischargeConcentration);

        if (data[i].pollutants == "ph") {
            var valueLow = parseFloat(data[i].limitValue.split('-')[0]);
            var valueUp = parseFloat(data[i].limitValue.split('-')[1]);
            if (value < valueLow || value > valueUp) {
                flag = 0;
                break;
            }
        } else {
            var limitValue = parseFloat(data[i].limitValue);
            if (value > limitValue) {
                flag = 0;
                break;
            }
        }
    }

    var result = document.getElementById("result");
    if (flag == 1) result.innerHTML = "达到排放要求";
    else result.innerHTML = "部分监测点未达到排放要求";
}
